package org.modulefusion.example.jpa.personprovider.impl;

import java.util.List;

import javax.persistence.EntityManager;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.modulefusion.example.jpa.personprovider.Person;
import org.modulefusion.example.jpa.personprovider.PersonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
@Provides
public class PersonServiceImpl implements PersonService {

    final Logger logger = LoggerFactory.getLogger(PersonServiceImpl.class);

    @Requires
    private EntityManager entityManager;

    
    public Person savePerson(Person person) {
        entityManager.getTransaction().begin();
        logger.info("save Person");
        Person newP = entityManager.merge(person);
        entityManager.getTransaction().commit();
        return newP;
    }
    
    public void deletePerson(Long id) {
        entityManager.getTransaction().begin();
        logger.info("delete Person");
        entityManager.remove(entityManager.find(Person.class, id));
        entityManager.getTransaction().commit();
    }

    public Person getPerson(Long id) {
        entityManager.getTransaction().begin();
        logger.info("get Person");
        Person person = entityManager.find(Person.class, id);
        entityManager.getTransaction().commit();
        return person;
    }

    @SuppressWarnings("unchecked")
    public List<Person> getPersonList() {
        entityManager.getTransaction().begin();
        logger.info("list all persons");
        List<Person> list = entityManager.createQuery("from Person").getResultList();
        
        entityManager.getTransaction().commit();
        return list;
    }
}
